package com.example.client_group5;

import java.net.URL;
import java.util.ArrayList;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.json.JSONArray;
import org.json.JSONObject;

import com.example.base.AppBaseActivity;

import util.HttpClientFactory;



import android.net.Uri;
import android.os.Bundle;
import android.content.Intent;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ProfileActivity extends AppBaseActivity {
	private RelativeLayout tweetDetail;
	private TextView usernameTile;
	private TextView fullnameTextView;
	private TextView usernameTextView;
	private TextView bio;
	private TextView location;
	private TextView web;
	private ImageView avatar;
	private String bioText;
	private String locationText;
	private String webText;
	private String[] infor;
	private String tweetCount;
	private String followingCount;
	private String followerCount;
	private View editProfile;
	private View follow;
	private boolean isFollowing;
	private ImageManager img;
	private UserManager userProfile;
	private Button tweetBt;
	private boolean isFoundUser = true;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//				WindowManager.LayoutParams.FLAG_FULLSCREEN);
//		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_user_timeline);
        registerBaseActivityReceiver();
        userProfile = SignInActivity.userProfile;
        Uri data = getIntent().getData();
        img = ImageManager.getInstance(getApplicationContext());
        if (data != null){
	        String url = data.toString();
	        String username = url.substring(url.indexOf("@")+1);
	        Log.d("mUser", "mUser: " + username);
	        isFoundUser = getUserProfile(username);
	        if(!isFoundUser){
	        	Toast toast = Toast.makeText(getApplicationContext(), "Can't load user info. Please try again later", Toast.LENGTH_LONG);
	        	toast.show();
	        	finish();
	        	Log.d("show", "Den day");
	        }
        }
        else{
	        Bundle b = getIntent().getExtras();
	        infor = b.getStringArray("user");
        }   
        if(isFoundUser){
        usernameTile = (TextView)findViewById(R.id.username_title);
        fullnameTextView = (TextView)findViewById(R.id.fullname);
        usernameTextView = (TextView)findViewById(R.id.username);
        avatar = (ImageView)findViewById(R.id.avatar_id);
    	ProgressBar progressBar=(ProgressBar)findViewById(R.id.progress_bar_id);
        if(infor != null){
        	usernameTile.setText(" @" + infor[2]);
        	fullnameTextView.setText(infor[1]);
        	usernameTextView.setText(" @" + infor[2]);
        	img.displayImage(infor[3], this,avatar, progressBar);
        	avatar.setTag(infor[3]);
        }
        usernameTile.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				closeAllActivities();
				
			}
		});
        tweetBt = (Button)findViewById(R.id.btTweet);
        tweetBt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent i = new Intent(ProfileActivity.this, TweetActivity.class);
				Bundle b = new Bundle();
				String[] replyInfo = {"follow"};
				b.putStringArray("reply", replyInfo);
				i.putExtras(b);
				startActivity(i);
//				finish();
			}
		});
        tweetDetail = (RelativeLayout)findViewById(R.id.tweet_detail);
        tweetDetail.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(ProfileActivity.this, ViewTweetUserActivity.class);
				Bundle b = new Bundle();
				b.putStringArray("owner", infor);
				i.putExtras(b);
				startActivity(i);
//				finish();
			}
		});
//        Log.d("tag", "user-id: " + infor[0]);
        
        ArrayList<Tweet> tweets = get3Tweet(infor[0]);
        
        bio = (TextView)findViewById(R.id.bio);
    	location = (TextView)findViewById(R.id.place);
    	web = (TextView)findViewById(R.id.web_id);
    	
    	
    	bio.setText(bioText);
    	location.setText(locationText);
 
    	web.setText(webText);
       
        if(tweets.size() > 0){
        	pushData(tweets);
        }
        else{
        	LinearLayout tweetLayout = (LinearLayout)findViewById(R.id.tile2);
        	tweetLayout.setVisibility(View.GONE);
        }
        
        TextView tweetCountText = (TextView)findViewById(R.id.tweet_count_id);
        tweetCountText.setText(tweetCount);
        
        TextView followingCountText = (TextView) findViewById(R.id.following_count_id);
        followingCountText.setText(followingCount);
        
        TextView followerCountText = (TextView) findViewById(R.id.followers_count_id);
        followerCountText.setText(followerCount);
        
        LinearLayout profileTweet = (LinearLayout)findViewById(R.id.profile_tweet_id);
        profileTweet.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(Integer.parseInt(tweetCount) > 0){
					Intent i = new Intent(ProfileActivity.this, ViewTweetUserActivity.class);
					Bundle b = new Bundle();
					b.putStringArray("owner", infor);
					i.putExtras(b);
					startActivity(i);
//					finish();
				}
			}
		});
        LinearLayout followingLayout = (LinearLayout)findViewById(R.id.following_id);
        followingLayout.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(Integer.parseInt(followingCount) > 0){
					Intent i = new Intent(ProfileActivity.this, FollowingActivity.class);
					Bundle b = new Bundle();
					b.putStringArray("owner", infor);
					i.putExtras(b);
					startActivity(i);
//					finish();
				}
			}
		});
        
        LinearLayout profileFollowing = (LinearLayout)findViewById(R.id.profile_following_id);
        profileFollowing.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(Integer.parseInt(followingCount) > 0){
					Intent i = new Intent(ProfileActivity.this, FollowingActivity.class);
					Bundle b = new Bundle();
					b.putStringArray("owner", infor);
					i.putExtras(b);
					startActivity(i);
//					finish();
				}
			}
		});
        
        
        LinearLayout followerLayout = (LinearLayout)findViewById(R.id.followers_id);
        followerLayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(Integer.parseInt(followerCount) > 0){
					Intent i = new Intent(ProfileActivity.this, FollowerActivity.class);
					Bundle b = new Bundle();
					b.putStringArray("owner", infor);
					i.putExtras(b);
					startActivity(i);
//					finish();
				}
			}
		});
        LinearLayout profileFollower = (LinearLayout)findViewById(R.id.profile_follower_id);
        profileFollower.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(Integer.parseInt(followerCount) > 0){
					Intent i = new Intent(ProfileActivity.this, FollowerActivity.class);
					Bundle b = new Bundle();
					b.putStringArray("owner", infor);
					i.putExtras(b);
					startActivity(i);
//					finish();
				}
			}
		});
        
        LinearLayout favoriteLayout = (LinearLayout)findViewById(R.id.favorites_id);
        favoriteLayout.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
//				Bundle b = new Bundle();
				// Truyen tham so
				Intent i = new Intent(ProfileActivity.this,FavoriteTweet.class); 
				Bundle b = new Bundle();
				b.putStringArray("user", infor);
				i.putExtras(b);
				startActivity(i);
//				finish();
			}
		});
        
        editProfile = (View)findViewById(R.id.editProfile);
        follow = (View)findViewById(R.id.follow_id);
        LinearLayout settingLayout = (LinearLayout)findViewById(R.id.layout_setting);
//        UserManager userProfile = new UserManager(this, "USER");
        String user_id = userProfile.getUserId("userId", "");
        if(user_id.equals(infor[0])){
        	editProfile.setVisibility(View.VISIBLE);
        	settingLayout.setVisibility(View.VISIBLE);
        	Log.d("msg", user_id + "/ " + infor[0]);
        	
        }
        else{
        	if(isFollowing){
        		follow.setBackgroundResource(R.drawable.following_bt);
        	}
        	else{
        		follow.setBackgroundResource(R.drawable.follow_bt);
        	}
        	follow.setVisibility(View.VISIBLE);
        	editProfile.setVisibility(View.GONE);
        	
        }
        
        editProfile.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(ProfileActivity.this, EditProfileActivity.class);
				Bundle b = new Bundle();
				b.putStringArray("profile", infor);
				i.putExtras(b);
				startActivity(i);
//				finish();
			}
		});
        
        
        follow.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(isFollowing){
					// Dang o trang thai following
					deleteFollowing(infor[0]);
					follow.setBackgroundResource(R.drawable.follow_bt);
					isFollowing = false;
				}
				else{
					// Dang o trang thai follow
					createFollowing(infor[0]);
					follow.setBackgroundResource(R.drawable.following_bt);
					isFollowing = true;
				}
			}
		});
        
        LinearLayout switchAccount = (LinearLayout)findViewById(R.id.profile_switch_id);
        switchAccount.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				
				
			}
		});
        
        LinearLayout removeAccount = (LinearLayout)findViewById(R.id.remove_id);
        removeAccount.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				logOut();
				Intent i = new Intent(ProfileActivity.this, SignInActivity.class);
				startActivity(i);
				finish();
			}
		});
        }
    }
   
    public ArrayList<Tweet> get3Tweet(String owner_id){
    	String url = Setting.ipServer + "api/user/show-user-info?user_id=" + owner_id;
    	ArrayList<Tweet> tweets = new ArrayList<Tweet>();
    	HttpGet get = new HttpGet(url);
		//HttpClientFactory clientFactory=new HttpClientFactory(); 
		HttpClient client = HttpClientFactory.getThreadSafeClient();
		ResponseHandler<String> responseHandler = 
		        new BasicResponseHandler();

		String responseBody = null;
		try {
		   responseBody = client.execute(get,responseHandler);
		} catch(Exception ex) {
			  ex.printStackTrace();
		}
		Log.d("tag", "fuck url:"+url);
		Log.d("tag", "Tra ve: " + responseBody);
		JSONObject jsonObject = null;
		try{
			jsonObject = new JSONObject(responseBody);
			Log.d("tag", jsonObject.toString());
			tweetCount = jsonObject.getString("tweet_count");
			followingCount = jsonObject.getString("following_count");
			followerCount = jsonObject.getString("follower_count");
			isFollowing = jsonObject.getBoolean("is_following");
			bioText = jsonObject.getString("bio");
			locationText = jsonObject.getString("address");
			webText = jsonObject.getString("web");
			JSONArray jsonArray = jsonObject.getJSONArray("recentTweets");
			
			for(int i = 0; i < jsonArray.length(); i ++){
				JSONObject t = jsonArray.getJSONObject(i);
				String content = t.get("content").toString().trim();
				String tweet_id = t.get("id").toString();
				String mention = t.get("mentions").toString();
				String time = t.get("created_time").toString();
//				boolean isRetweeted = t.getBoolean("is_retweeted");
//				boolean isFavorite = t.getBoolean("is_favorite");
//				String retweetedUser = t.getString("retweeted_user");
				
				
				String user_id = t.get("user_id").toString();
				String username = t.get("username").toString();
				
				String fullname = t.get("fullname").toString();
				
				
				String profile_url = t.get("avatar").toString();
				Log.d("tag", profile_url);
				Tweet tweet = new Tweet(tweet_id, fullname, username, user_id, mention, content, "", profile_url, time, false, false, "");
				tweets.add(tweet);
				
			}
		}catch(Exception e){
			e.printStackTrace();
		}
    	return tweets;
    }
    
    public void pushData(ArrayList<Tweet> tweets){
    	LinearLayout sampleLayout = null;
    	ImageView avatar;
  		TextView fullname;
  		TextView usernamae;
  		TextView content;
  		ProgressBar progressBar;
		for(int i = 0; i < tweets.size(); i ++){
			final Tweet tweet = tweets.get(i);
	      	if(i == 0){
	      		sampleLayout = (LinearLayout)findViewById(R.id.sample_id1);
	      		sampleLayout.setVisibility(View.VISIBLE);
	      		avatar = (ImageView)findViewById(R.id.avatar);
	      		progressBar=(ProgressBar)findViewById(R.id.progress_bar);
	      		fullname = (TextView)findViewById(R.id.fullname_tweet);
	      		usernamae = (TextView)findViewById(R.id.username_tweet);
	      		content = (TextView)findViewById(R.id.message);
	      	
	      		img.displayImage(tweet.image_url, this, avatar, progressBar);
	      		avatar.setTag(tweet.image_url);
	      		fullname.setText(tweet.fullname);
	      		usernamae.setText("@" + tweet.username);
	      		content.setText(tweet.content);
	      		
	      	}
	      	if(i == 1){
	      		sampleLayout = (LinearLayout)findViewById(R.id.sample_id2);
	      		sampleLayout.setVisibility(View.VISIBLE);
	      		avatar = (ImageView)findViewById(R.id.avatar1);
	      		progressBar=(ProgressBar)findViewById(R.id.progress_bar1);
	      		fullname = (TextView)findViewById(R.id.fullname_tweet1);
	      		usernamae = (TextView)findViewById(R.id.username_tweet1);
	      		content = (TextView)findViewById(R.id.message1);
	      	
	      		img.displayImage(tweet.image_url, this, avatar, progressBar);
	      		avatar.setTag(tweet.image_url);
	      		fullname.setText(tweet.fullname);
	      		usernamae.setText("@" + tweet.username);
	      		content.setText(tweet.content);
	      	}
	      	if(i == 2){
	      		sampleLayout = (LinearLayout)findViewById(R.id.sample_id3);
	      		sampleLayout.setVisibility(View.VISIBLE);
	      		avatar = (ImageView)findViewById(R.id.avatar2);
	      		progressBar=(ProgressBar)findViewById(R.id.progress_bar2);
	      		fullname = (TextView)findViewById(R.id.fullname_tweet2);
	      		usernamae = (TextView)findViewById(R.id.username_tweet2);
	      		content = (TextView)findViewById(R.id.message2);
	      	
	      		img.displayImage(tweet.image_url, this, avatar, progressBar);
	      		avatar.setTag(tweet.image_url);
	      		fullname.setText(tweet.fullname);
	      		usernamae.setText("@" + tweet.username);
	      		content.setText(tweet.content);
	      	}
	      	if(sampleLayout != null){
	      		sampleLayout.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						Intent i = new Intent(ProfileActivity.this, TweetDetail.class);
						Bundle b = new Bundle();
						String[] info = {tweet.tweet_id, tweet.fullname, tweet.username, tweet.content, tweet.time, "" + tweet.isRetweeted, "" + tweet.isFavorite,
										tweet.retweetedUser, tweet.user_id, tweet.image_url, tweet.img_up_url};
						b.putStringArray("tweet", info);
						i.putExtras(b);
						startActivity(i);
//						finish();
					}
				});
	      	}
	    }
	    
    }
    public void createFollowing(String user_id){
    	String url = Setting.ipServer + "api/user/follow?user_id=" + user_id;
    	HttpGet get = new HttpGet(url);
		 
		ResponseHandler<String> responseHandler = 
		        new BasicResponseHandler();

		String responseBody = null;
		try {
		    responseBody = HttpClientFactory.getThreadSafeClient().execute(get, responseHandler);
		    
		} catch(Exception ex) {
			  ex.printStackTrace();
		}
		Log.d("tag", "Tra ve: " + responseBody);
		
    }
    public void deleteFollowing(String user_id){
    	String url = Setting.ipServer + "/api/user/un-follow?user_id=" + user_id;
    	HttpGet get = new HttpGet(url);
    	ResponseHandler<String> responseHandler = 
		        new BasicResponseHandler();

		String responseBody = null;
		try {
		    responseBody = HttpClientFactory.getThreadSafeClient().execute(get, responseHandler);
		    
		} catch(Exception ex) {
			  ex.printStackTrace();
		}
		Log.d("tag", "Tra ve: " + responseBody);
    	
    }
    public boolean getUserProfile(String username){
    	String url = Setting.ipServer + "api/user/show-user-info?username=" + username;
    	HttpGet get = new HttpGet(url);
		 
		ResponseHandler<String> responseHandler = 
		        new BasicResponseHandler();

		String responseBody = null;
		try {
		    responseBody = HttpClientFactory.getThreadSafeClient().execute(get, responseHandler);
		    
		} catch(Exception ex) {
			  ex.printStackTrace();
		}
		
		Log.d("tag", "Tra ve: " + responseBody);
		JSONObject jsonObject = null;
		try{
			jsonObject = new JSONObject(responseBody);
			if(jsonObject.getBoolean("isFound")){
				String user_id = jsonObject.getString("id");
				String fullname = jsonObject.getString("fullname");
				String avatar = jsonObject.getString("avatar");
				infor = new String[]{user_id, username, fullname, avatar};
				Log.d("return", "Return true" );
				return true;
			}
			//Log.d("tag", jsonObject.toString());
		}catch(Exception e){
			e.printStackTrace();
		}
		Log.d("return", "Return false" );
		return false;
    }
    public void logOut(){
    	String url = Setting.ipServer + "/api/auth/logout";
    	HttpGet logout = new HttpGet(url);
    	ResponseHandler<String> responseHandler = new BasicResponseHandler();
    	try{
    		HttpClientFactory.getThreadSafeClient().execute(logout, responseHandler);
    		
    	}catch(Exception e){
    		e.printStackTrace();
    	}
		userProfile.removeUser();
		Log.d("fuck", "fuck: " + userProfile.getUserName("username", ""));
    }
    public int getPosition(String userId){
    	int count = LazyLoading.adapter.getCount();
    	for(int position = 0; position < count; position ++){
    		Tweet elTweet = LazyLoading.adapter.getItem(position);
    		if(elTweet.user_id.equals(userId)){
    			return position;
    		}
    	}
    	return -1;
    }
    
    public boolean onKeyDown(int keycode, KeyEvent event){
		if(keycode == KeyEvent.KEYCODE_BACK){
			finish();
		}
    	return false;
    }
    public void onDestroy(){
    	super.onDestroy();
    	System.gc();
    	unRegisterBaseActivityReceiver();
    }
   

}
